package com.lv.suyiyong.hfr.ui

import android.content.pm.ActivityInfo
import android.text.Editable
import android.text.TextWatcher
import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lv.common.base.BaseActivity
import com.lv.common.imp.UploadFileListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.setSafeListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.DesUtil
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxNetUtilsKt
import com.lv.common.utils.picengine.CompressEngine
import com.lv.common.utils.picengine.GlideEngine
import com.lv.common.utils.showToast
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserInfo
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityPerfectUserinfoBinding
import com.lv.suyiyong.hfr.moudel.MainViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import okhttp3.RequestBody
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * 作者： ygx
 * 创建日期：2023/3/2 7:26 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：完善信息
 */
@Route(path = ARoutUtils.PerfectUserInfoActivity)
class PerfectUserInfoActivity : BaseActivity<ActivityPerfectUserinfoBinding>(),
    View.OnClickListener {
    @Autowired(name = "showLogin")
    @JvmField
    var mShowLogin = false
    private val mSelectMedia = mutableListOf<LocalMedia?>()
    private var isShowPassWord: Boolean = false
    private var isShowPassWordCon: Boolean = false
    private var mUserInfo: UserInfo? = null
    private val viewModel: MainViewModel by viewModel()
    private val viewModelService: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_perfect_userinfo
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = viewModel
            StatusBarUtil.setHeightAndPadding(this@PerfectUserInfoActivity, titleBar)
            ivLogo.setOnClickListener(this@PerfectUserInfoActivity)
            ivEyes.setOnClickListener(this@PerfectUserInfoActivity)
            ivEyesCon.setOnClickListener(this@PerfectUserInfoActivity)
            etPhone.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//                    etPhone.paint.isFakeBoldText = !TextUtils.isEmpty(s)
                    if (s.length == 11) {
                        etCode.requestFocus()
                    }

                }

                override fun afterTextChanged(s: Editable) {
                }
            })


            mBinding.btnLogin.setSafeListener {

                val password = viewModel.obPassword.get()
                val password_ = viewModel.obPasswordCon.get()
                val name = viewModel.obMobile.get()
                if (password != password_) {
                    showToast("输入的密码不一致")
                } else {
                    aliUpNet(name ?: "", password ?: "")
                }
            }
            tvLogin.setSafeListener {
                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
                finish()
            }

            mBinding.titleBar.setRightBarDec(true)
            mBinding.titleBar.setRightBarDec("跳过")
            mBinding.titleBar.setTitle("完善信息")
            mBinding.titleBar.onClickBackIcon { finish() }
            mBinding.titleBar.onClickRightTitle() { finish() }

        }
    }

    override fun initConfig() {
        super.initConfig()
        mBinding.tvLogin.visibility = if (mShowLogin) View.VISIBLE else View.GONE
        mUserInfo = intent.getParcelableExtra<UserInfo>("userInfo")
        viewModel.obMobile.set(mUserInfo?.name)
        mBinding.ivLogo.LoadSrc(mUserInfo?.logo)

    }

    private fun aliUpNet(name: String, password: String) {
        lifecycleScope.launchWhenCreated {
            if (mSelectMedia.isEmpty()) {
                upDataUser(name, password)
            } else {
                val mMedias = mutableListOf<LocalMedia?>()
                mMedias.addAll(mSelectMedia)
                withContext(Dispatchers.IO) {
                    YgxNetUtilsKt.partFilesToAli(
                        this@PerfectUserInfoActivity, mSelectMedia = mMedias,
                        uploadFileListener = object : UploadFileListener {
                            override fun uploadSuccess(list: List<String>, listString: String) {
                                super.uploadSuccess(list, listString)
                                upDataUser(name, password, listString)
                            }

                            override fun uploadFailed(message: String) {
                                super.uploadFailed(message)
                                loadFinished()
                            }
                        })
                }
            }
        }
    }

    private fun upDataUser(name: String, password: String, listString: String? = "") {
        startLoading()
        val partMap = HashMap<String, RequestBody>()
        partMap["userid"] = YgxNetUtilsKt.partToRequestBody(mUserInfo?.id!!)
        partMap["password"] = YgxNetUtilsKt.partToRequestBody(DesUtil.encode(password))
        partMap["name"] = YgxNetUtilsKt.partToRequestBody(name)
        if (!listString.isNullOrEmpty()) {
            partMap["image"] = YgxNetUtilsKt.partToRequestBody(listString)
        }
        updateUser(partMap)
    }

    private fun updateUser(partMap: HashMap<String, RequestBody>) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModelService.updateUser(partMap) }.await()
            parseUpdateUserResult(result)
        }
    }

    private fun parseUpdateUserResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                showToast("注册成功，请登录")
                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
                finish()
            }
            onBizError<Any> { code, message, data ->
                showToast(message)

            }
        }
    }

    private fun login(res: UserInfo?) {
        res?.let {
//            SPStaticUtils.put(SP_KEY_USER_TOKEN, it.token)
            // 在用户 UI 点击登录的时候调用
//            login(
//                this@PerfectUserInfoActivity,
//                GenerateTestUserSig.SDKAPPID,
//                it.txaccid,
//                it.txaccidpassword,
//                object : TUICallback() {
//                    override fun onError(code: Int, desc: String) {
//                        LogUtils.e("onError")
//                    }
//
//                    override fun onSuccess() {
//                        UserDbHelper.insertUserInfo(this@PerfectUserInfoActivity, res)
//                        LogUtils.e("onSuccess")
//                        finish()
//                    }
//                })
        }
    }

    override fun initData() {
        super.initData()

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.iv_eyes -> {
                isShowPassWord = !isShowPassWord
                if (isShowPassWord) {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etCode.transformationMethod = null
                } else {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etCode.transformationMethod = PasswordTransformationMethod()
                }
            }

            R.id.iv_eyes_con -> {
                isShowPassWordCon = !isShowPassWordCon
                if (isShowPassWordCon) {
                    mBinding.ivEyesCon.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etCodeCon.transformationMethod = null
                } else {
                    mBinding.ivEyesCon.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etCodeCon.transformationMethod = PasswordTransformationMethod()
                }
            }

            R.id.iv_logo -> {
                checkPermission()
            }

        }
    }

    private fun checkPermission() {
        PermissionXUtils.checkPermissionCameraRead(
            this,
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        showPicSelector()
                    }
                }

                override fun fotPermsission() {
                }
            })
    }

    private fun showPicSelector() {
        PictureSelector.create(this@PerfectUserInfoActivity)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(CompressEngine.createCompressEngine())
            .setMaxSelectNum(1)
            .setMinSelectNum(1)
            .setImageSpanCount(4)
            .isPreviewImage(true) // 是否可预览图片
            .isDisplayCamera(true) // 是否显示拍照按钮
            .isOriginalSkipCompress(true) // 是否压缩
            .setSelectedData(mSelectMedia)
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.let {
                        mSelectMedia.clear()
                        mSelectMedia.addAll(it)
                        Glide.with(this@PerfectUserInfoActivity).load(mSelectMedia[0]?.compressPath)
                            .into(mBinding.ivLogo)
                    }
                }

                override fun onCancel() {}
            })


    }

}